//
//  StoreService.swift
//  Loop
//
//  Created by thomas on 2020/9/23.
//

import CoreData

extension NSNotification.Name {
    public static let StoreServiceDidInsertRequestNotification = NSNotification.Name("StoreServiceDidInsertRequestNotification")
}

class StoreService {

    static let shared = StoreService()

    private init() {}

    private lazy var persistentContainer: NSPersistentContainer = {

        let container = NSPersistentContainer(name: "Loop")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
}

// MARK: - Request Management
extension StoreService {

    /// 插入新的请求到历史数据
    /// - Parameters:
    ///   - task: 请求对应的task
    ///   - date: 请求产生的时间
    func insertRequest(_ task: URLSessionDataTask, date: Date) {

        let request = NSEntityDescription.insertNewObject(forEntityName: "GithubRequest", into: persistentContainer.viewContext) as? GithubRequest

        request?.id = Int64(task.taskIdentifier)
        request?.time = date
        request?.data = task.debugDescription

        NotificationCenter.default.post(name: .StoreServiceDidInsertRequestNotification,
                                        object: nil)
    }


    /// 根据id查找对应的历史请求对象
    /// - Parameter id: 需要查找的请求所对应的id
    /// - Returns: 对应于id的历史请求对象
    func getRequestHistory(by id: Int64) -> GithubRequest? {

        let request: NSFetchRequest = GithubRequest.fetchRequest()
        request.fetchLimit = 1
        request.predicate = NSPredicate(format: "id=%u", id)
        do {
            let result: [GithubRequest] = try persistentContainer.viewContext.fetch(request)
            return result.first
        } catch {
            fatalError();
        }
    }

    /// 获取所有请求历史列表（按时间倒序）
    /// - Returns: 所有请求历史列表
    func getAllRequestHistory() -> [GithubRequest]? {

        let request: NSFetchRequest = GithubRequest.fetchRequest()
        request.sortDescriptors = [NSSortDescriptor(key: "time", ascending: false)]
        do {
            let result: [GithubRequest] = try persistentContainer.viewContext.fetch(request)
            return result
        } catch {
            fatalError();
        }
    }
}

// MARK: - Result Management
extension StoreService {


    /// 插入请求结果到历史数据
    /// - Parameters:
    ///   - errorMsg: 请求出错时的错误信息
    ///   - data: 请求成功时返回的data
    ///   - date: 请求产生的时间
    func insertRequestResult(errorMsg: String?, data: Data?, date: Date) {

        let request = NSEntityDescription.insertNewObject(forEntityName: "GithubRequestResult", into: persistentContainer.viewContext) as? GithubRequestResult

        request?.time = date
        request?.errorMsg = errorMsg
        request?.data = data
    }


    /// 获取所有请求结果历史列表（按时间倒序）
    /// - Returns: 所有请求结果历史列表
    func getAllRequestResultHistory() -> [GithubRequestResult]? {

        let request: NSFetchRequest = GithubRequestResult.fetchRequest()
        request.sortDescriptors = [NSSortDescriptor(key: "time", ascending: false)]
        do {
            let result: [GithubRequestResult] = try persistentContainer.viewContext.fetch(request)
            return result
        } catch {
            fatalError();
        }
    }

    /// 根据date查找对应的历史请求对象
    /// - Parameter date: 需要查找的请求所对应的date
    /// - Returns: 对应于date的历史请求对象
    func getRequestResultHistory(by date: Date) -> GithubRequestResult? {

        let request: NSFetchRequest = GithubRequestResult.fetchRequest()
        request.fetchLimit = 1
        request.predicate = NSPredicate(format: "time == %@", date as NSDate)
        do {
            let result: [GithubRequestResult] = try persistentContainer.viewContext.fetch(request)
            return result.first
        } catch {
            fatalError();
        }
    }

    /// 获取最后一条请求结果记录
    /// - Returns: 最后一条请求结果记录
    func getLastRequestResult() -> GithubRequestResult? {

        let request: NSFetchRequest = GithubRequestResult.fetchRequest()
        request.fetchLimit = 1
        request.sortDescriptors = [NSSortDescriptor(key: "time", ascending: false)]
        do {
            let result: [GithubRequestResult] = try persistentContainer.viewContext.fetch(request)
            return result.first
        } catch {
            fatalError();
        }
    }
}
